﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Net.Sockets;

namespace eHouse
{
    public partial class RulePage : PhoneApplicationPage
    {
        public RulePage()
        {
            InitializeComponent();

            NewRuleImage.ImageSource = new System.Windows.Media.Imaging.BitmapImage(new Uri("AddRule" + App.IconToUse + ".png", UriKind.RelativeOrAbsolute));
            SaveImage.ImageSource = new System.Windows.Media.Imaging.BitmapImage(new Uri("SaveToCloud" + App.IconToUse + ".png", UriKind.RelativeOrAbsolute));

            DataContext = App.RuleModel;
            PageTitle.Text = App.SchedulingSensor;
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);

            fadeAnimation.Stop();
            Storyboard.SetTarget(fadeAnimation, PopupBorder);
            Storyboard.SetTargetProperty(fadeIn, new PropertyPath(UIElement.OpacityProperty));
            Storyboard.SetTargetProperty(fadeOut, new PropertyPath(UIElement.OpacityProperty));
            fadeOut.Completed += new EventHandler((object o, EventArgs args) =>
            {
                ToastPopup.IsOpen = false;
            });

        }

        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {

            if (App.RuleModel.Error)
            {
                App.RuleModel.Error = false;
                MessageBox.Show("There has been an error in the connection. Check your internet connection and try again");
                NavigationService.GoBack();
                return;
            }

            if (App.SchedulingSensor == "Temperature" && App.RuleModel.Rules.Count > 0)
            {
                newRule.Visibility = Visibility.Collapsed;
            }
        }

        private readonly object _lock = new object();
        Storyboard fadeAnimation = new Storyboard();
        DoubleAnimation fadeIn = new DoubleAnimation()
        {
            Duration = new Duration(TimeSpan.FromMilliseconds(500)),
            From = 0.00,
            To = 1.00
        };
        DoubleAnimation fadeOut = new DoubleAnimation()
        {
            Duration = new Duration(TimeSpan.FromMilliseconds(500)),
            From = 1.00,
            To = 0.00
        };

        private void RemoveRule_Click(object sender, RoutedEventArgs e)
        {
            Button button = (Button)sender;
            button.IsEnabled = false;
            newRule.IsEnabled = false;
            saveToCloud.IsEnabled = false;
            string tag = button.Tag.ToString();
            EventHandler<SocketAsyncEventArgs> onServerRespondedListener =
                new EventHandler<SocketAsyncEventArgs>((object o, SocketAsyncEventArgs async) =>
                {
                    System.Threading.Thread t = new System.Threading.Thread(() =>
                    {
                        lock (_lock)
                        {
                            Dispatcher.BeginInvoke(() =>
                            {
                                fadeAnimation.Stop();
                                fadeAnimation.Children.Clear();
                                fadeAnimation.Children.Add(fadeIn);

                                string message;
                                if (async.SocketError == SocketError.Success)
                                {
                                    ItemViewModel remove = null;
                                    foreach (ItemViewModel item in App.RuleModel.Rules)
                                    {
                                        if (item.SwitchState == tag)
                                        {
                                            remove = item;
                                            break;
                                        }
                                    }
                                    App.RuleModel.Rules.Remove(remove);
                                    ruleList.UpdateLayout();
                                    if (App.RuleModel.Rules.Count == 0)
                                    {
                                        newRule.Visibility = Visibility.Visible;
                                    }
                                    message = "Rule successfully deleted";
                                }
                                else
                                {
                                    message = "An error occurred deleting the rule. Please, try again later";
                                    button.IsEnabled = true;
                                }

                                newRule.IsEnabled = true;
                                saveToCloud.IsEnabled = true;
                                ToastMessage.Text = message;
                                ToastPopup.IsOpen = true;

                                fadeAnimation.Begin();
                            });
                            System.Threading.Thread.Sleep(2500);
                            Dispatcher.BeginInvoke(() =>
                            {
                                fadeAnimation.Stop();
                                fadeAnimation.Children.Clear();
                                fadeAnimation.Children.Add(fadeOut);
                                fadeAnimation.Begin();
                            });
                            System.Threading.Thread.Sleep(500);
                        }
                    });
                    t.Name = "Toast control";
                    t.Start();
                });

            new System.Threading.Thread(() =>
            {
                App.ConnectionManager.RemoveRule(App.SchedulingSensor, tag, onServerRespondedListener);
            }).Start();
        }

        private void newRule_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Schedule" + App.SchedulingSensor + ".xaml", UriKind.RelativeOrAbsolute));
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            WaitingScreen.savedWindow = "/RulePage.xaml";
            if (App.RuleAdderCall != null)
            {
                newRule.IsEnabled = false;
                saveToCloud.IsEnabled = false;
                EventHandler<SocketAsyncEventArgs> onServerRespondedListener =
                new EventHandler<SocketAsyncEventArgs>((object o, SocketAsyncEventArgs async) =>
                {
                    System.Threading.Thread t = new System.Threading.Thread(() =>
                    {
                        lock (_lock)
                        {
                            Dispatcher.BeginInvoke(() =>
                            {
                                fadeAnimation.Stop();
                                fadeAnimation.Children.Clear();
                                fadeAnimation.Children.Add(fadeIn);

                                string message;
                                if (async.SocketError == SocketError.Success)
                                {
                                    if (App.SchedulingSensor == "Temperature" && App.RuleModel.Rules.Count > 0)
                                    {
                                        newRule.Visibility = Visibility.Collapsed;
                                    }
                                    ItemViewModel item = new ItemViewModel();
                                    item.LineOne = App.RuleForSaving.Time;
                                    item.LineTwo = App.RuleForSaving.ToString();
                                    item.SwitchState = App.RuleForSaving.Id;
                                    App.RuleModel.Rules.Add(item);
                                    message = "Rule successfully added";
                                }
                                else
                                {
                                    message = "An error occurred adding the rule. Please, try again later";
                                }

                                newRule.IsEnabled = true;
                                saveToCloud.IsEnabled = true;
                                ToastMessage.Text = message;
                                ToastPopup.IsOpen = true;

                                fadeAnimation.Begin();
                            });
                            System.Threading.Thread.Sleep(2500);
                            Dispatcher.BeginInvoke(() =>
                            {
                                fadeAnimation.Stop();
                                fadeAnimation.Children.Clear();
                                fadeAnimation.Children.Add(fadeOut);
                                fadeAnimation.Begin();
                            });
                            System.Threading.Thread.Sleep(500);
                        }
                    });
                    t.Name = "Toast control";
                    t.Start();
                });

                new System.Threading.Thread(() =>
                {
                    App.RuleAdderCall(App.RuleForSaving, onServerRespondedListener);
                    App.RuleAdderCall = null;
                }).Start();

            }
        }

        private void saveToCloud_Click(object sender, RoutedEventArgs e)
        {
            Dispatcher.BeginInvoke(() =>
            {
                WaitingScreen.nextWindow = "/RulePage.xaml";
                WaitingScreen.waitingTask = new WaitingScreen.WaitingTask(() =>
                {
                    App.Service.SaveRules(App.SchedulingSensor);
                    if (App.Service.Error)
                    {
                        MessageBox.Show("An error ocurred saving the rules. Please, try again later");
                    }
                    Dispatcher.BeginInvoke(() =>
                    {
                        NavigationService.RemoveBackEntry();
                    });
                });
                NavigationService.Navigate(new Uri("/WaitingScreen.xaml", UriKind.RelativeOrAbsolute));
            });
        }
    }
}